<template>
  <div class="floating-cart" @click="goToCart">
    <div class="cart-icon">
      <i class="fas fa-shopping-cart"></i>
      <span class="cart-count" v-if="cartCount > 0">{{ cartCount }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const cartCount = ref(0)

const updateCartCount = () => {
  const cart = JSON.parse(localStorage.getItem('cart') || '[]')
  cartCount.value = cart.length
}

onMounted(updateCartCount)

// 监听localStorage变化
watchEffect(() => {
  window.addEventListener('storage', updateCartCount)
  return () => window.removeEventListener('storage', updateCartCount)
})

const goToCart = () => {
  router.push('/cart')
}
</script>

<style scoped>
.floating-cart {
  position: fixed;
  right: 30px;
  bottom: 30px;
  background: #42b983;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
  transition: transform 0.3s;
  z-index: 1000;
}

.floating-cart:hover {
  transform: scale(1.1);
}

.cart-icon {
  position: relative;
  color: white;
  font-size: 24px;
}

.cart-count {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #ff5252;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 18px;
  text-align: center;
}
</style>
